import { Graph, NodeData } from "@antv/g6";
import { useCallback, useEffect, useRef } from "react";

interface INodeData extends NodeData {
  data?: { label: string; width: number; height: number };
}

const ChartDemo1 = () => {
  const ref = useRef<HTMLDivElement & { graph?: Graph }>(null);

  const getData = useCallback(() => {
    return fetch("https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json")
      .then((res) => res.json())
      .then((data) => {
        const graph = ref.current.graph;
        graph.setData(data);
        graph.render();
      });
  }, []);

  useEffect(() => {
    const graph = new Graph({
      container: ref.current,
      background: "#F2F7FA",
      autoFit: "center",
      modes: {
        default: [
          {
            type: "collapse-expand",
            onChange: function onChange(item, collapsed) {
              const data = item.get("model");
              data.collapsed = collapsed;
              return true;
            }
          },
          "drag-canvas",
          "zoom-canvas"
        ]
      },
      defaultNode: {
        size: 26,
        anchorPoints: [
          [0, 0.5],
          [1, 0.5]
        ]
      },
      defaultEdge: {
        type: "cubic-horizontal"
      },
      layout: (layoutData) => {
        const compactBox = new Hierachy.dendrogram(layoutData, { nodeSep: 50 });
        const positions = {};
        G6.Util.traverseTree(compactBox, (child) => {
          positions[child.id] = { x: child.x, y: child.y };
        });
        let subGraph = {};
        G6.Util.traverseTree(layoutData, (child) => {
          if (child.id === "Classification") subGraph = child;
          child.x = positions[child.id].x;
          child.y = positions[child.id].y;
        });
        const mindmap = new Hierachy.mindmap(subGraph, {
          direction: "RL",
          getHGap: (d) => 50
        });
        console.log("subGraph", compactBox, subGraph);
        G6.Util.traverseTree(mindmap, (child) => {
          positions[child.id] = { x: child.x, y: child.y };
        });
        G6.Util.traverseTree(compactBox, (child) => {
          child.x = positions[child.id].x;
          child.y = positions[child.id].y;
        });

        console.log("layoutData", compactBox, layoutData);

        return compactBox;
      }
      animation: false,
    });
    ref.current.graph = graph;
    graph.render();

    getData();
  }, []);

  return (
    <>
      <h2>官方：图布局 Dagre</h2>
      <div ref={ref} style={{ width: "100%", minHeight: 600 }}></div>
    </>
  );
};

export default ChartDemo1;
